/*
 *  @Title FileValidator.java
 *  @Package： com.phoenix.core.annotation.impl
 *  Copyright (c) 2017 by 江苏深南互联网金融信息服务有限公司  All right reserved
 */
package com.phoenix.core.annotation.impl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.phoenix.core.annotation.File;

/**
 *  @ClassName FileValidator
 *  @Description 文件验证只验证是否上传文件不用传验证传值使用图标标准类型如是
 *  @author liuwb
 *  @version 1.0
 *  @date 2017年6月27日
 */
public class FileValidator implements ConstraintValidator<File, CommonsMultipartFile> {

	private String types;

	private boolean isValidateTypes;

	private boolean isValidateEmpty;

	private long size;

	private String message;

	@Override
	public void initialize(File constraintAnnotation) {
		message = constraintAnnotation.message();
		size = constraintAnnotation.size();
		types = constraintAnnotation.types();
		isValidateTypes = constraintAnnotation.isValidateTypes();
		isValidateEmpty = constraintAnnotation.isValidateEmpty();
	}

	@Override
	public boolean isValid(CommonsMultipartFile value, ConstraintValidatorContext context) {
		// 验证是否为空文件
		if (isValidateEmpty) {
			if (value == null || value.isEmpty())
				return Boolean.FALSE;
		} else
			return Boolean.TRUE;
		// 验证类型
		if (isValidateTypes) {
			if (types != null && types.indexOf(value.getContentType()) == -1) {
				if (StringUtils.isBlank(message)) {
					context.buildConstraintViolationWithTemplate("{constraints.default.File.type.message}")
							.addConstraintViolation();
					context.disableDefaultConstraintViolation();
				}
				return Boolean.FALSE;
			}
		}
		// 验证文件大小
		if (size != 0) {
			if (value.getSize() > size) {
				if (StringUtils.isBlank(message)) {
					context.buildConstraintViolationWithTemplate("{constraints.default.File.size.message}")
							.addConstraintViolation();
					context.disableDefaultConstraintViolation();
				}
				return Boolean.FALSE;
			}
		}
		return Boolean.TRUE;
	}

}
